package com.allen.study.domain.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @ClassName: CustomExecutionListener
 * @Author: AllenSun
 * @Date: 2025/2/23 下午9:11
 */
@Slf4j
@Component
public class MultiInstanceEndListener implements TaskListener {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public MultiInstanceEndListener(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("开始判断会签审批结果");
        log.info("节点：name :{}, id: {} 监听, 开始，监听类型 -> {}", delegateTask.getName(), delegateTask.getId(),
                delegateTask.getEventName());

        String ACT_APPROVAL_COUNT_KEY = StrUtil.format("{}:{}:approvalCount",delegateTask.getProcessInstanceId(),
                delegateTask.getName());

        // 获取当前任务的所有表单参数
        Map<String, Object> formVariables = delegateTask.getVariables();

        // 输出所有表单参数
        for (Map.Entry<String, Object> entry : formVariables.entrySet()) {
            String variableName = entry.getKey();
            Object variableValue = entry.getValue();
            System.out.println("表单参数名: " + variableName + ", 参数值: " + variableValue);
        }

        // 一个审批节点的多个审批人的审批结果累加，到下一个节点的时候清空，或者使用redis的计数器实现
        Integer approvalCount = 0;
        Boolean approvalResult = (Boolean)delegateTask.getVariable("approvalResult");
        if(ObjectUtil.isNotNull(approvalResult) && approvalResult){
            redisTemplate.opsForValue().increment(ACT_APPROVAL_COUNT_KEY, 1);
        }
        approvalCount = (Integer) redisTemplate.opsForValue().get(ACT_APPROVAL_COUNT_KEY);
        delegateTask.setVariable("approvalCount",approvalCount);

        // 实例总数
        Integer nrOfInstances = (Integer) delegateTask.getVariable("nrOfInstances");
        delegateTask.setVariable("instanceCount",nrOfInstances);

        log.info("{} 会签审批结果，通过人数{}/实例总数{}",delegateTask.getName(),approvalCount,nrOfInstances);

    }
}
